package com.xinziruo.crawl.infrastruture.messaging.event;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

import com.xinziruo.crawl.domain.crawl.CrawlApiObject;
import com.xinziruo.crawl.domain.crawl.api.CrawlEvent;
import com.xinziruo.crawl.domain.crawl.api.CrawlEventHandler;
import com.xinziruo.crawl.infrastruture.support.command.impl.CrawlCommand;
import com.xinziruo.crawl.infrastruture.support.server.CommandServerBroker;
import com.xinziruo.crawl.infrastruture.util.JsonUtils;

/**
 * 
 * @author loudyn
 * 
 */
public class CrawlEventHandlerImpl implements CrawlEventHandler, InitializingBean {
	private static final Logger LOGGER = LoggerFactory.getLogger(CrawlEventHandlerImpl.class);

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.youboy.crawl.domain.crawl.api.CrawlEventHandler#handle(com.youboy
	 * .crawl.domain.crawl.api.CrawlEvent)
	 */
	@Override
	public void handle(CrawlEvent crawlEvent) throws Exception {
		final CrawlApiObject api = (CrawlApiObject) crawlEvent.getMessage();

		handler.submit(new Runnable() {

			@Override
			public void run() {

				try {

					String jsonString = JsonUtils.toJsonString(api);
					commandServerBroker.writeCommand(new CrawlCommand().content(jsonString.getBytes("utf-8")));
				} catch (Exception e) {
					//LOGGER.info("error occur!", e);
				}
			}

		});

	}

	@Override
	public void afterPropertiesSet() throws Exception {
		handler = Executors.newFixedThreadPool(handlerThreadSize);
	}

	private ExecutorService handler;

	private CommandServerBroker commandServerBroker;
	private int handlerThreadSize = 20;

	public void setCommandServerBroker(CommandServerBroker commandServerBroker) {
		this.commandServerBroker = commandServerBroker;
	}

	public void setHandlerThreadSize(int handlerThreadSize) {
		Assert.isTrue(handlerThreadSize > 0, "handerThreadSize must gt 0!");
		this.handlerThreadSize = handlerThreadSize;
	}

}
